import { Command } from '../constant';
import Taro from '@tarojs/taro';
import { Dispatch } from 'typings';
import { IAllReducerProps } from '../types';
import { getReducerData } from '@/redux/store';
import { extraPathsValue } from '@/redux/util';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async page() {
      let uniqueID = Taro.getStorageSync('uniqueID')
      let params = {
        deviceNum: uniqueID,
      };
      let res = await api.pointsMallController.getCateList(params);
      if (res.pointsGoodsCateVOList.length > 0) {
        let titleList = [];
        res.pointsGoodsCateVOList.map((item) => {
          let obj = { title: '' }
          obj.title = item.cateName
          titleList.push(obj)
        })
        action.commonChange([
          { paths: 'main.tabList', value: res.pointsGoodsCateVOList },
          { paths: 'main.titleList', value: titleList },
          { paths: 'main.selectId', value: res.pointsGoodsCateVOList[0].cateId },
          { paths: 'main.pageNum', value: 0 },
        ]);
        // 查询积分商品列表
        this.findPointsMall();
      }
    },
    async findPointsMall() {
      let { selectId, pageNum, leftData, rightData } = getData().main;
      let params = {
        cateId: selectId,
        goodsName: "",
        keywords: "",
        pageNum,
        pageSize: 16,
        sortFlag: 0,
      };
      let result = await api.pointsMallController.page(params)
      if (result.pointsGoodsVOPage.content.length > 0) {
        let rows = result.pointsGoodsVOPage.content;
        let leftData = [], rightData = [];
        rows.map((item, index) => {
          if (index % 2 == 0) {
            leftData.push(item)
          } else {
            rightData.push(item)
          }
        });
        if (pageNum == 0) {
          action.commonChange('main.leftData', leftData);
          action.commonChange('main.rightData', rightData);
          action.commonChange('main.totalPages', result.pointsGoodsVOPage.totalPages);
        } else {
          let newLeftData = leftData.concat(leftData);
          let newRightData = rightData.concat(rightData);
          action.commonChange('main.leftData', newLeftData);
          action.commonChange('main.rightData', newRightData);
          action.commonChange('main.totalPages', result.pointsGoodsVOPage.totalPages);
        }
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageBIntegralGoodsMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
